package com.heroCW.bodhiAttic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heroCW.bodhiAttic.entity.Employee;
import com.heroCW.bodhiAttic.mapper.EmployeeMapper;
import com.heroCW.bodhiAttic.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Override
    public IPage<Employee> getPage(int page, int pageSize, String name) {
        log.info("用户名:{}",name);
        // 构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.apply("lower(NAME) LIKE CONCAT(CONCAT('%',{0}),'%')", name.toLowerCase());
            queryWrapper.or().apply("lower(USERNAME) LIKE CONCAT(CONCAT('%',{0}),'%')", name.toLowerCase());
        }
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //构造分页构造器
        IPage<Employee> pageInfo = new Page<>(page, pageSize);

        return this.page(pageInfo, queryWrapper);
    }

    @Override
    public Employee getEmployeeByUsername(String username) {
        // 根据username查询用户
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,username);
        return this.getOne(queryWrapper);
    }

    @Override
    public Boolean updateUser(Employee employee) {

        String password = employee.getPassword();
        if (StringUtils.isNotEmpty(password)) {
            employee.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        } else {
            employee.setPassword(this.getById(employee.getId()).getPassword());
        }

        return this.updateById(employee);
    }
}
